import React, { useEffect, useState } from 'react'
import { Menu, Layout } from 'antd'
import './SideMenu.less'
import axios from 'axios'
import base from '../routes/baseUrl'
import { HomeOutlined, SolutionOutlined, TeamOutlined, UserAddOutlined } from '@ant-design/icons'
import { useLocation, useNavigate } from 'react-router'

const { Sider } = Layout

const iconList = {
  '/home': <HomeOutlined />,
  '/select-teacher': <TeamOutlined />,
  '/selected': <SolutionOutlined />,
  '/student-list': <UserAddOutlined />
}

export default function SideMenu(props) {

  const [menu, setMenu] = useState([]) // 侧边栏
  const location = useLocation() // useLocation Hook，获取当前地址
  const [currentRole, setCurrentRole] = useState([]) // 获取当前角色权限用
  const selectedKeys = [location.pathname]
  const openKeys = ['/' + location.pathname.split('/')[1]] // 为pathname前加斜线
  const navigate = useNavigate()
  const { userType, teacherId } = JSON.parse(sessionStorage.getItem('token'))

  const click = (e) => {
    navigate(e.key)
  }

  useEffect(() => {
    axios.get(base + `/roles/${userType}`).then(res => {
      setCurrentRole(res.data)
    })
  }, [userType])

  useEffect(() => {
    axios.get(base + '/rights').then(res => {
      if (teacherId !== 904) { // 已选择导师则不展示“导师列表”
        setMenu(res.data.filter(item => item.key !== '/select-teacher'))
      } else {
        setMenu(res.data)
      }
    })
  }, [teacherId])

  return (
    <Sider trigger={null} collapsible collapsed={props.collapsed}>
      <div style={{
        display: 'flex',
        height: '100%',
        flexDirection: 'column',
        textAlign: 'center',
        overflow: 'hidden'
      }}>
        <div className="logo">
          <a href="https://www.nefu.edu.cn" target='_blank' rel='noreferrer'><img src="./assets/nefu_logo_white.webp" alt="logo" id='logo-pic' /></a>
          <h2 style={{
            color: 'whitesmoke',
            wordBreak: 'keep-all',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis'
          }}>毕设选导师系统</h2>
        </div>
        <Menu
          mode='inline'
          theme='dark'
          onClick={click}
          defaultOpenKeys={openKeys} // 默认打开的组件
          selectedKeys={selectedKeys}
          items={menu.map(item => {
            // console.log(item.key)
            // 仅展示当前角色有的权限
            // 将icon映射到侧边栏中
            return currentRole.rights.includes(item.key) ? { ...item, icon: iconList[item.key] } : undefined
          })}
        />
      </div>
    </Sider>
  )
}
